
package com.example.haohao.myview;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.TransformationMethod;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.internal.functions.Functions;

public class DropDownEditTextView extends LinearLayout implements View.OnClickListener, TextWatcher {

    private Context mContext;

    private int height;

    private boolean isLayoutWeight = false;

    private boolean isArrowPadding = false;

    private boolean isCursorVisible = true;

    private boolean isEdit = true;

    private int edtTextSize;

    private int edtTextColor;

    private int edtHintTextColor;

    private int imgIcon_down;

    private int imgIcon_up;

    private EditText mEditText;

    private ImageView mImageView;

    private ColorStateList mEditTextColor;
    private View mPopupView;
    private PopupWindow mPopupWindow = null;
    private FixItemListView listView;
    private MyListAdapter mMyListAdapter;
    private EditText destET;
    private int mPrePosition = -1;
    private TextView pop_tv_title;
    private ImageView pop_img_close;

    public DropDownEditTextView(Context context) {
        this(context, null);
    }

    public DropDownEditTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DropDownEditTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DropDownEditTextView);
        height = typedArray.getLayoutDimension(R.styleable.DropDownEditTextView_android_layout_height, -2);
        isLayoutWeight = typedArray.getBoolean(R.styleable.DropDownEditTextView_layout_is_weight, false);
        isArrowPadding = typedArray.getBoolean(R.styleable.DropDownEditTextView_layout_is_arrow_padding, false);
        isCursorVisible = typedArray.getBoolean(R.styleable.DropDownEditTextView_layout_is_cursorVisible, true);
        edtTextColor = typedArray.getColor(R.styleable.DropDownEditTextView_layout_edt_text_color, getResources().getColor(R.color.color_333333));
        edtHintTextColor = typedArray.getColor(R.styleable.DropDownEditTextView_layout_edt_text_color, getResources().getColor(R.color.color_999999));
        edtTextSize = typedArray.getInteger(R.styleable.DropDownEditTextView_layout_edt_text_size, 15);
        imgIcon_down = typedArray.getResourceId(R.styleable.DropDownEditTextView_layout_img_icon, height != -2 ? R.mipmap.img_arrow_down : R.mipmap.img_rectangle_down);
        imgIcon_up = height != -2 ? R.mipmap.dzh_up : R.mipmap.rectangle_up;
        isEdit = typedArray.getBoolean(R.styleable.DropDownEditTextView_layout_edt_is_edit, true);
        typedArray.recycle();
        setOrientation(LinearLayout.HORIZONTAL);
        init();
    }

    @Override
    public void onClick(View v) {

        if (mMyListAdapter.getCount() > 0) {
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                //mImageView.setImageResource(R.drawable.trade_dropdown);
                mPopupWindow.dismiss();
            } else if (mMyListAdapter.getCount() > 1) {
//                当前显示的选项就是条目1，所以要大于1才可以设置图标点击后 向上
                if (isArrowPadding) {
                    mImageView.setImageResource(imgIcon_up);
                }
                //mImageView.setImageResource(R.drawable.trade_dropup);
                hideSoftKeyBoard();
                openPopupWindow();
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (mAddTextChangedListener != null) {
            mAddTextChangedListener.onTextChanged(s, start, before, count);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        refitText(mEditText.getWidth());
    }

    private void init() {
        // TODO: 2021/6/12 居中问题
        LayoutParams layoutParams_edt = null;
        if (isLayoutWeight) {
            layoutParams_edt = new LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams_edt.weight = 3;
        } else {
            if (height == -2) {
                layoutParams_edt = new LayoutParams(0, 105);
                layoutParams_edt.weight = 3;
            } else {
                layoutParams_edt = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            }
        }
        layoutParams_edt.setMargins(0, 0, 0, 0);
        layoutParams_edt.gravity = Gravity.CENTER_VERTICAL;
        mEditText = new EditText(mContext);
        mEditText.setPadding(0, 0, 0, 0);
        mEditText.setBackgroundColor(Color.TRANSPARENT);
        mEditText.setCursorVisible(isCursorVisible);
        mEditText.setHintTextColor(edtHintTextColor);
        mEditText.setTextColor(edtTextColor);
        mEditText.setTextSize(edtTextSize);
        mEditText.setGravity(Gravity.CENTER_VERTICAL);
        mEditText.setSingleLine(true);
        mEditText.setEllipsize(TextUtils.TruncateAt.END);
        mEditTextColor = mEditText.getTextColors();
        mEditText.addTextChangedListener(this);
        addView(mEditText, layoutParams_edt);

        LayoutParams layoutParams_img ;
        mImageView = new ImageView(mContext);
        if (!isLayoutWeight) {
            // TODO: 2021/6/12
            layoutParams_img = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//            layoutParams_img.setMargins(DensityUtils.dp2px(10), 0, DensityUtils.dp2px(10), 0);
            layoutParams_img.setMargins(10, 0, 0, 0);
        }else if (isArrowPadding){
            layoutParams_img = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mImageView.setPadding(DensityUtils.dp2px(10),DensityUtils.dp2px(10),DensityUtils.dp2px(10),DensityUtils.dp2px(10));
        }else {
            layoutParams_img = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        }
        layoutParams_img.gravity = Gravity.CENTER_VERTICAL;
        mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        mImageView.setImageResource(imgIcon_down);
        addView(mImageView, layoutParams_img);

        if (!isEdit) {
            mEditText.setFocusableInTouchMode(false);
            mEditText.setClickable(false);
            mEditText.setFocusable(false);
            mEditText.setMovementMethod(null);
            mEditText.setKeyListener(null);
            setOnClickListener(this);
        }
        mImageView.setOnClickListener(this);

        mMyListAdapter = new MyListAdapter();
        mPopupView = LayoutInflater.from(getContext()).inflate(R.layout.dropdown_edittext_popup,null);
        pop_tv_title = (TextView) mPopupView.findViewById(R.id.tv_title_popup_bottom);
        pop_img_close = (ImageView) mPopupView.findViewById(R.id.img_close);
        listView = mPopupView.findViewById(R.id.dropdown_listview);
        listView.setAdapter(mMyListAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isArrowPadding) {
                    mImageView.setImageResource(imgIcon_down);
                }
                String str = dataList.get(position);
                mEditText.setText(str);
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
                if (position != realPosition) {
                    realPosition = position;
                }
                if (mOnItemChangeListener != null && position != mCurrentPosition) {
                    mOnItemChangeListener.onItemChange(str, position);
                }
                mPrePosition = mCurrentPosition;
                mCurrentPosition = position;
                mMyListAdapter.setCurPosition(position);
                if (mPrePosition != mCurrentPosition) {
                    if (destET != null)
                        destET.setText("");
                }
            }
        });
        pop_img_close.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isArrowPadding) {
                    mImageView.setImageResource(imgIcon_down);
                }
                mPopupWindow.dismiss();
            }
        });
    }

    private void hideSoftKeyBoard() {
//        ActivityManager.getInstance().getCurrentActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//        InputMethodManager imm = (InputMethodManager) ActivityManager.getInstance().getCurrentActivity().getSystemService(
//                Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    public void setPop_tv_title(String pop_title) {
        this.pop_tv_title.setText(pop_title);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (map.get(mEditText.getText().toString()) == null)
            refitText(getWidth());
    }

    private Map<String, Float> map = new HashMap<String, Float>();

    private void refitText(int textWidth) {
        if (textWidth > 0) {
            int availableWidth = textWidth - mEditText.getPaddingLeft() - mEditText.getPaddingRight();
            TextPaint paint = mEditText.getPaint();
            float mTextSize = mEditText.getTextSize();
            float minSize = 11;
            while (paint.measureText(mEditText.getText().toString()) > availableWidth) {
                mTextSize = mTextSize - 1;
                paint.setTextSize(mTextSize);
                if (mTextSize <= DensityUtils.sp2px( minSize))
                    break;
            }
            mEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
            map.put(mEditText.getText().toString(), mTextSize);
        }
    }

/*    private void dimBackground(PopupWindow popup, float dimAmount) {
        ViewParent vp;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            vp = popup.getContentView().getParent().getParent();
        } else {
            vp = popup.getContentView().getParent();
        }
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        if (vp instanceof View) {
            // PopupWindow has background drawable set
            View container = (View) vp;
            WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
            p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            p.dimAmount = dimAmount;
            wm.updateViewLayout(container, p);
        } else {
            // PopupWindow has no background drawable
            WindowManager.LayoutParams p =
                    (WindowManager.LayoutParams) popup.getContentView().getLayoutParams();
            p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            p.dimAmount = dimAmount;
            wm.updateViewLayout(popup.getContentView(), p);
        }
    }*/

    //设置选择图标
    public void setSelectIcon(int id) {
        if (id > 0) {
            mImageView.setImageResource(id);
        }
    }

    /**
     * 设置成无边框
     */
//    public void setNoFrame() {
//        setBackgroundResource(R.drawable.dropdown_editview_bg2);
//    }

    public void setCanDropDown(boolean b) {
        if (b) {
            mImageView.setVisibility(VISIBLE);
        } else {
            mImageView.setVisibility(GONE);
        }
    }

    private void openPopupWindow() {
        listView.setFixItemCount(5);
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(mPopupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setTouchable(true);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    bgAlpha(1f);
                    if (isArrowPadding) {
                        mImageView.setImageResource(imgIcon_down);
                    }

                }
            });
        }
        bgAlpha(0.5f);
/*        if (dataList != null && dataList.size() > 5) {
            mPopupWindow.setHeight(MZBannerView.dpToPx(300));
        } else {
            mPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
        }*/
        mPopupWindow.showAsDropDown(this);


/*        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(mPopupView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setTouchable(true);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            //设置了dismisslistener后PopupWindow弹出时会比较慢，不明原因。。。
//            mPopupWindow.setOnDismissListener(new OnDismissListener() {
//
//                @Override
//                public void onDismiss() {
//                    // TODO Auto-generated method stub
//                    mImageView.setImageResource(R.drawable.trade_dropdown);
//                }
//            });
        }

        if (mMyListAdapter.getCount() != 0) {
            //item个数过多时可能由于软键盘遮挡而无法点击到最后一个item
            if (dataList.size() > 10) {
                mPopupWindow.setHeight(SettingManager.getInstance().getScreenHeight() / 2);
            }
            mMyListAdapter.notifyDataSetChanged();
            mPopupWindow.showAsDropDown(this);
            dimBackground(mPopupWindow, 0.35f);
        }*/
    }


    private void bgAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
        lp.alpha = bgAlpha;
        ((Activity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        ((Activity) mContext).getWindow().setAttributes(lp);
    }

    private int realPosition = -1;
    private int mCurrentPosition = -1;
    private ArrayList<String> dataList = null;

    /**
     * 设置下拉列表自动显示下拉按钮
     *
     * @param list
     * @param position
     */
    public void setDropDownListData(ArrayList<String> list, int position, boolean needItemChange) {
        dataList = list;
        if (list != null && list.size() != 0) {
            setCanDropDown(true);
            String str = "";
            realPosition = position;
            mCurrentPosition = position;
            mMyListAdapter.setCurPosition(position);
            str = list.get(position);

            mEditText.setText(str);
            if (mOnItemChangeListener != null && needItemChange) {
                mOnItemChangeListener.onItemChange(list.get(position), position);
            }
        } else {
            mEditText.setText("");
            realPosition = -1;
            mCurrentPosition = -1;
        }

        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }

    /**
     * 设置当前选中项
     *
     * @param p
     */
    public void setCurrentPositon(int p) {
        mCurrentPosition = p;
        mMyListAdapter.setCurPosition(p);
    }

    boolean mCanDel = false;

    public void setCanDelItem(boolean candel) {
        mCanDel = true;
    }

    public void setTransformationMethod(TransformationMethod method) {
        if (mEditText != null) {
            mEditText.setTransformationMethod(method);
        }
    }

    public void clearData() {
        dataList = null;
        mEditText.setText("");
        realPosition = -1;
        mCurrentPosition = -1;
    }

    public class MyListAdapter extends BaseAdapter {

        private int curPosition = 0;
        private int colorSelected;
        private int colorUnSelected;

        public MyListAdapter() {
            colorSelected = mContext.getResources().getColor(R.color.colorRed);
            colorUnSelected = mContext.getResources().getColor(R.color.color_333333);
        }

        public void setCurPosition(int curPosition) {
            this.curPosition = curPosition;
        }

        @Override
        public int getCount() {
            if (dataList == null || dataList.size() < 1) {
                return 0;
            } else {
                return dataList.size();
            }
        }

        @Override
        public Object getItem(int position) {
            if (dataList == null || dataList.size() < 1) {
                return null;
            } else {
                return dataList.get(position);
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.dropdown_list_item,
                        null);
                holder = new Holder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.image = (ImageView) convertView.findViewById(R.id.image);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            holder.text.setText(dataList.get(position));
            if (curPosition == position) {
                holder.text.setTextColor(colorSelected);
            } else {
                holder.text.setTextColor(colorUnSelected);
            }
            if (mCanDel) {
                holder.image.setVisibility(VISIBLE);
            } else {
                holder.image.setVisibility(GONE);
            }
            holder.image.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    if (mOnListItemImageClickListener != null) {
                        mOnListItemImageClickListener.onItemImageClick(dataList.get(position));
                    }
                    if (mPopupWindow != null && mPopupWindow.isShowing()) {
                        mPopupWindow.dismiss();
                    }
                }
            });
            return convertView;
        }

        class Holder {
            TextView text;
            ImageView image;
        }

    }

    public void setEditable(boolean enable) {
        if (enable) {
            mEditText.setTextColor(mEditTextColor);
        } else {//保证不可编辑时文字颜色不变
            mEditText.setTextColor(mEditTextColor.getDefaultColor());
        }
        mEditText.setEnabled(enable);
    }

    public EditText getEditText() {
        return mEditText;
    }

    /**
     * 调用此方法隐藏下拉按钮
     *
     * @param text
     */
    public void setText(String text) {
        // TODO Auto-generated method stub
        setCanDropDown(false);
        mEditText.setText(text);
    }

    public void setDestET(EditText destET) {
        this.destET = destET;
        mPrePosition = -1;
    }

/*    public void setLarge() {
        LinearLayout.LayoutParams rlp = (LayoutParams) mEditText.getLayoutParams();
        rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        mEditText.setLayoutParams(rlp);
        mEditText.setGravity(Gravity.CENTER);
        mEditText.setTextSize(20);
    }*/

    /**
     * 调用此方法清空当前edittext显示的数据，下拉框中的数据保留
     */
    public void clearCurrentText() {
        mEditText.setText("");
        realPosition = -1;
        mCurrentPosition = -1;
    }

    AddTextChangedListener mAddTextChangedListener;

    public void setAddTextChangedListener(AddTextChangedListener addTextChangedListener) {
        // TODO Auto-generated method stub
        mAddTextChangedListener = addTextChangedListener;
    }


    OnItemChangeListener mOnItemChangeListener;

    public void setOnItemChangeListener(OnItemChangeListener onItemChangeListener) {
        // TODO Auto-generated method stub
        mOnItemChangeListener = onItemChangeListener;
    }

    public OnItemChangeListener getOnItemChangeListener() {
        return mOnItemChangeListener;
    }

    OnListItemImageClickListener mOnListItemImageClickListener;

    public void setOnListItemImageClickListener(OnListItemImageClickListener onListItemImageClickListener) {
        mOnListItemImageClickListener = onListItemImageClickListener;
    }

    public String getCurrentItem() {
        // TODO Auto-generated method stub
        return mEditText.getText().toString();
    }

    public ArrayList<String> getDataList() {
        // TODO Auto-generated method stub
        return dataList;
    }

    public int getRealPosition() {
        return realPosition;
    }

    public int getSelectedItemPosition() {
        // TODO Auto-generated method stub
        return mCurrentPosition;
    }

    public interface OnItemChangeListener {
        public void onItemChange(String item, int position);
    }

    public interface OnListItemImageClickListener {
        public void onItemImageClick(String item);
    }

    public interface AddTextChangedListener {
        public void onTextChanged(CharSequence s, int start, int before, int count);
    }

}
